/*
 * #%L
 * SwiftUIDataAccessLayer
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
/**
 * 
 */
package com.linkwithweb.products.swiftui.service.impl;

import java.io.OutputStream;
import java.security.KeyPair;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.linkwithweb.products.swiftui.context.DBUpdateStatement;
import com.linkwithweb.products.swiftui.context.ExcelFile;
import com.linkwithweb.products.swiftui.context.QueryContext;
import com.linkwithweb.products.swiftui.context.SystemContext;
import com.linkwithweb.products.swiftui.dao.PlatformDAO;
import com.linkwithweb.products.swiftui.dataobject.FrameworkApplication;
import com.linkwithweb.products.swiftui.dataobject.FrameworkBackup;
import com.linkwithweb.products.swiftui.dataobject.FrameworkEvent;
import com.linkwithweb.products.swiftui.dataobject.FrameworkEventScheduler;
import com.linkwithweb.products.swiftui.dataobject.FrameworkForm;
import com.linkwithweb.products.swiftui.dataobject.FrameworkFormField;
import com.linkwithweb.products.swiftui.dataobject.FrameworkLOV;
import com.linkwithweb.products.swiftui.dataobject.FrameworkLOVValue;
import com.linkwithweb.products.swiftui.dataobject.FrameworkMenu;
import com.linkwithweb.products.swiftui.dataobject.FrameworkReportColumn;
import com.linkwithweb.products.swiftui.dataobject.FrameworkTable;
import com.linkwithweb.products.swiftui.dataobject.FrameworkTextReport;
import com.linkwithweb.products.swiftui.dataobject.FrameworkTransaction;
import com.linkwithweb.products.swiftui.dataobject.FrameworkUpload;
import com.linkwithweb.products.swiftui.dataobject.FrameworkUser;
import com.linkwithweb.products.swiftui.dataobject.FrameworkWorkflow;
import com.linkwithweb.products.swiftui.service.PlatformService;
import com.linkwithweb.products.swiftui.spring.jdbc.ColumnMetadata;
import com.linkwithweb.products.swiftui.spring.jdbc.DatabaseResult;
import com.linkwithweb.products.swiftui.spring.jdbc.MapObject;
import com.linkwithweb.products.swiftui.ui.model.RequestCondition;
import com.linkwithweb.products.swiftui.utils.DateUtils;
import com.linkwithweb.products.swiftui.utils.FreeMarkerEngine;
import com.linkwithweb.products.swiftui.utils.JCryptionUtil;
import com.linkwithweb.products.swiftui.utils.ServiceLocator;
import com.linkwithweb.products.swiftui.utils.SystemConstants;
import com.linkwithweb.products.swiftui.utils.SystemConstants.ConditionalConstants;

/**
 * @author ashwin
 * 
 */
@Service("platformService")
public class PlatformServiceImpl extends AbstractServiceImpl implements PlatformService {
	protected final Log logger = LogFactory.getLog(getClass());
	private PlatformDAO platformDAO;
	@Value("${framework.dbType}")
	private String dbType;

	/**
	 * @return the platformDAO
	 */
	public PlatformDAO getPlatformDAO() {
		if (platformDAO == null) {
			platformDAO = (PlatformDAO) ServiceLocator.getService("platformDAO");
		}
		return platformDAO;

	}

	/**
	 * @param platformDAO
	 *            the platformDAO to set
	 */
	public void setPlatformDAO(PlatformDAO platformDAO) {
		this.platformDAO = platformDAO;
	}

	/**
	 * * (non-Javadoc)
	 * 
	 * @see com.linkwithweb.framework.service.PlatformService#loadResult(java.lang .String)
	 */
	public DatabaseResult loadResult(String sql, String dataSourceTemplate) {
		return loadResult(sql, dataSourceTemplate, new ArrayList());
	}

	/**
	 * * (non-Javadoc)
	 * 
	 * @see com.linkwithweb.framework.service.PlatformService#loadResult(java.lang .String, long, long)
	 */
	public DatabaseResult loadResult(String sql, String dataSourceTemplate, long fromIndex, long toIndex) {
		return getPlatformDAO().loadResult(sql, dataSourceTemplate, fromIndex, toIndex);
	}

	public DatabaseResult loadResult(String sql, String dataSourceTemplate, List values, long fromIndex, long toIndex) {
		return getPlatformDAO().loadResult(sql, dataSourceTemplate, values, fromIndex, toIndex);
	}

	/**
	 * * (non-Javadoc)
	 * 
	 * @see com.linkwithweb.framework.service.PlatformService#loadResult(java.lang .String, java.util.List)
	 */
	public DatabaseResult loadResult(String sql, String dataSourceTemplate, List values) {
		return getPlatformDAO().loadResult(sql, dataSourceTemplate, values);
	}

	/**
	 * * (non-Javadoc)
	 * 
	 * @see com.linkwithweb.framework.service.PlatformService#queryForInt(java.lang .String, java.util.List)
	 */
	public int queryForInt(String sql, String dataSourceTemplate, List values) {
		return getPlatformDAO().queryForInt(sql, dataSourceTemplate, values);
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.linkwithweb.framework.service.PlatformService#getTableNames()
	 */
	public List<String> getTableNames(String dataSourceTemplate) {
		return getPlatformDAO().getTableNames(dataSourceTemplate);
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.northalley.framework.service.PlatformService#loadResult(com.northalley .framework.context.QueryContext)
	 */
	public DatabaseResult loadResult(QueryContext queryContext, String dataSourceTemplate) {
		return getPlatformDAO().loadResult(queryContext, dataSourceTemplate);
	}

	/**
	 * * (non-Javadoc)
	 * 
	 * @see com.northalley.framework.service.PlatformService#update(java.lang.String, boolean, java.lang.Object[])
	 */
	public void update(String sql, String dataSourceTemplate, Object[] args) {
		getPlatformDAO().update(sql, dataSourceTemplate, args);

	}

	/**
	 * * (non-Javadoc)
	 * 
	 * @see com.northalley.framework.service.PlatformService#saveAndGetKey(java.lang .String, boolean, java.lang.Object[])
	 */
	public Long saveAndGetKey(final String sql, String dataSourceTemplate, final Object[] args) {
		return getPlatformDAO().saveAndGetKey(sql, dataSourceTemplate, args);
	}

	/**
	 * * (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#loadForm(java .lang.String)
	 */
	public FrameworkForm loadForm(String id) {
		FrameworkForm form = null;

		form = getPlatformDAO().loadForm(id);
		if (form != null) {

			// Set the table which related to this report
			form.setFrameworkTable(getPlatformDAO().loadFrameworkTable(form.getTableId()));

			/**
			 * Load Default Configuraton from Database metadata
			 */
			if (form.getFormFields() == null || form.getFormFields().isEmpty()) {
				DatabaseResult databaseResult = null;
				if (StringUtils.equalsIgnoreCase(form.getFrameworkTable().getTableType(),
						SystemConstants.EntityTypes.TABLE_DBOBJECT)) {
					databaseResult = loadResult("SELECT * FROM " + form.getFrameworkTable().getTableSchema() + "." + id
							+ " LIMIT 0,1", "jdbcTemplate");
				} else if (StringUtils.equalsIgnoreCase(form.getFrameworkTable().getTableType(),
						SystemConstants.EntityTypes.TABLE_DBSQL)) {
					databaseResult = loadResult(form.getFrameworkTable().getTableSQL() + " LIMIT 0,1", "jdbcTemplate");
				}
				if (databaseResult != null) {
					convertColumnMetaDataToFieldMetaData(databaseResult, form);
				}
			}

			/**
			 * Override default Configuration with custom Configuration Columns
			 * for Report
			 */
			List<FrameworkFormField> formFields = getPlatformDAO().loadFormFields(id);

			for (FrameworkFormField formField : formFields) {
				form.addField(formField);
			}

		}
		return form;
	}

	/**
	 * @param databaseResult
	 * @param form
	 */
	private void convertColumnMetaDataToFieldMetaData(DatabaseResult databaseResult, FrameworkForm form) {
		int order = 0;
		for (ColumnMetadata columnMetadata : databaseResult.getMetadata().getColumnsList()) {
			if (isSystemColumn(columnMetadata.getColumnName())) {
				continue;
			}

			FrameworkFormField formField = new FrameworkFormField();
			formField.setFieldName(columnMetadata.getColumnName());
			formField.setFieldLabel(columnMetadata.getColumnLabel());
			formField.setFieldType(columnMetadata.getColumnTypeName());
			formField.setActive(true);
			formField.setFieldDescription(columnMetadata.getColumnName());
			formField.setFieldId(columnMetadata.getColumnName());
			formField.setDisplayOrder(order);
			formField.setFormId(form.getFormId());
			formField.setRequired(!columnMetadata.isNullable());
			form.getFormFields().add(formField);
			order = order + 1;
		}
	}

	/*
	 * (non-Javadoc) Load Report and also load Report Columns and Search Fields
	 * For given Report
	 * 
	 * @see
	 * com.automata.framework.service.PlatformService#loadReport(java.lang
	 * .String)
	 */
	public FrameworkTextReport loadReport(String id) {
		/*
		 * FrameworkTextReport frameworkTextReport = FrameworkMetaDataCache
		 * .getInstance().getReportCache().get(id);
		 */
		FrameworkTextReport frameworkTextReport = null;

		if (frameworkTextReport == null) {
			frameworkTextReport = getPlatformDAO().loadReport(id);
			if (frameworkTextReport != null) {

				// Set the table which related to this report
				frameworkTextReport.setFrameworkTable(getPlatformDAO()
						.loadFrameworkTable(frameworkTextReport.getTableId()));

				String datasourceName = getDataSourceName(frameworkTextReport);
				/**
				 * Load Default Configuraton from Database metadata
				 */
				if (frameworkTextReport.getColumns() == null
						|| frameworkTextReport.getColumns().isEmpty()) {

					String sql = "";

					DatabaseResult databaseResult = null;
					if (StringUtils.equalsIgnoreCase(frameworkTextReport
							.getFrameworkTable().getTableType(),
							SystemConstants.EntityTypes.TABLE_DBOBJECT)) {
						sql = "SELECT * FROM "
								+ frameworkTextReport.getFrameworkTable()
										.getTableSchema()
								+ "."
								+ frameworkTextReport.getFrameworkTable()
										.getTableName();

					} else {
						sql = frameworkTextReport.getFrameworkTable()
								.getTableSQL();
					}

					String finalSQL = "";
					String primaryKey = frameworkTextReport.getFrameworkTable()
							.getPrimaryKeyColumn();
					String sord = "ASC";
					int offset = 0;
					int endRow = 1;

					/**
					 * Surround SQL with a outer SQL
					 */
					String intermittentSQL = "SELECT X.* FROM ( " + sql
							+ " ) X ";

					FrameworkApplication app = SystemContext.getInstance()
							.getUserContext().getFrameworkUser()
							.getListOfApplications().get(0);

					String dbMode = "MYSQL";

					if (StringUtils.equals(getDataSourceName(frameworkTextReport), "frameworkJdbcTemplate")) {
						dbMode = dbType;
					} else {
						dbMode = app.getDatasourceType();
					}

					if (StringUtils.equalsIgnoreCase(dbMode,
							SystemConstants.DBTypes.ORACLE)) {
						if (StringUtils.isNotBlank(frameworkTextReport
								.getOrderByCluase())) {
							intermittentSQL = sql + " ORDER BY "
									+ frameworkTextReport.getOrderByCluase();
							intermittentSQL = "SELECT * FROM  ( SELECT  a.*, ROWNUM RowNumber FROM ( "
									+ intermittentSQL
									+ " ) a  WHERE ROWNUM < "
									+ endRow
									+ " ) WHERE RowNumber >= "
									+ offset;
						} else {
							intermittentSQL = "SELECT * FROM  ( SELECT  a.*, ROWNUM RowNumber FROM ( "
									+ sql
									+ " ) a  WHERE ROWNUM < "
									+ endRow
									+ " ) WHERE RowNumber >= " + offset;
						}

						finalSQL = intermittentSQL;

						finalSQL = finalSQL.replaceAll("`", "");
					} else if (StringUtils.equalsIgnoreCase(
							dbMode,
							SystemConstants.DBTypes.SQLSERVER)) {
						intermittentSQL = intermittentSQL.replaceFirst(
								"SELECT",
								"SELECT ROW_NUMBER() OVER ( ORDER BY "
										+ primaryKey + " " + sord
										+ " ) AS RowNumber,");

						finalSQL = "SELECT RowConstrainedResult.* FROM ("
								+ intermittentSQL
								+ " )  RowConstrainedResult WHERE RowNumber > "
								+ offset + " AND RowNumber <= " + endRow
								+ " ORDER BY RowNumber";

						finalSQL = finalSQL.replaceAll("`", "\"");
					} else if (StringUtils.equalsIgnoreCase(
							dbMode,
							SystemConstants.DBTypes.MYSQL)) {
						if (StringUtils.isNotBlank(frameworkTextReport
								.getOrderByCluase())) {
							finalSQL = intermittentSQL + " ORDER BY "
									+ frameworkTextReport.getOrderByCluase()
									+ " LIMIT " + offset + " ," + endRow;
						} else {
							finalSQL = intermittentSQL + " LIMIT " + offset
									+ " ," + endRow;
						}
					}

					databaseResult = loadResult(finalSQL, datasourceName);

					convertColumnMetaDataToReportMetaData(databaseResult,
							frameworkTextReport);

				}

				/**
				 * Override default Configuration with custom Configuration
				 * Columns for Report
				 */
				List<FrameworkReportColumn> reportColumns = getPlatformDAO()
						.loadReportColumns(id);

				for (FrameworkReportColumn reportColumn : reportColumns) {
					frameworkTextReport.addColumn(reportColumn);
				}

				// Load Rico Table Once
				frameworkTextReport.getRicoTable();
				// Store in Cache
				// FrameworkMetaDataCache.getInstance().storeReport(id,
				// frameworkTextReport);
			}
		}
		return frameworkTextReport;
	}

	/**
	 * @param reportSQL
	 * @return
	 */
	public FrameworkTextReport loadReportFromSQL(String reportSQL) {
		/*
		 * FrameworkTextReport frameworkTextReport = FrameworkMetaDataCache
		 * .getInstance().getReportCache().get(id);
		 */
		FrameworkTextReport frameworkTextReport = null;

		if (frameworkTextReport == null) {
			frameworkTextReport = new FrameworkTextReport();
			frameworkTextReport.setReportId("QUERY_"
					+ SystemContext.getInstance().getClientName().get());
			frameworkTextReport.setReportName("Query");
			frameworkTextReport.setTableId(frameworkTextReport.getReportId());
			frameworkTextReport.setReportHeading(frameworkTextReport
					.getReportId());
			if (frameworkTextReport != null) {

				FrameworkTable frameworkTable = new FrameworkTable();
				frameworkTable.setTableId(frameworkTextReport.getReportId());
				frameworkTable.setTableName(frameworkTextReport.getReportId());
				frameworkTable.setTableSQL(reportSQL);
				frameworkTextReport.setFrameworkTable(frameworkTable);
				// Set the table which related to this report

				String datasourceName = "jdbcTemplate";
				/**
				 * Load Default Configuration from Database metadata
				 */
				if (frameworkTextReport.getColumns() == null
						|| frameworkTextReport.getColumns().isEmpty()) {

					String sql = "";

					DatabaseResult databaseResult = null;
					if (StringUtils.equalsIgnoreCase(frameworkTextReport
							.getFrameworkTable().getTableType(),
							SystemConstants.EntityTypes.TABLE_DBOBJECT)) {
						sql = "SELECT * FROM "
								+ frameworkTextReport.getFrameworkTable()
										.getTableSchema()
								+ "."
								+ frameworkTextReport.getFrameworkTable()
										.getTableName();

					} else {
						sql = frameworkTextReport.getFrameworkTable()
								.getTableSQL();
					}

					String finalSQL = "";
					String primaryKey = frameworkTextReport.getFrameworkTable()
							.getPrimaryKeyColumn();
					String sord = "ASC";
					int offset = 0;
					int endRow = 1;

					/**
					 * Surround SQL with a outer SQL
					 */
					String intermittentSQL = "SELECT X.* FROM ( " + sql
							+ " ) X ";

					FrameworkApplication app = SystemContext.getInstance()
							.getUserContext().getFrameworkUser()
							.getListOfApplications().get(0);

					String dbMode = "MYSQL";

					if (StringUtils.equals(getDataSourceName(frameworkTextReport), "frameworkJdbcTemplate")) {
						dbMode = dbType;
					} else {
						dbMode = app.getDatasourceType();
					}

					if (StringUtils.equalsIgnoreCase(dbMode,
							SystemConstants.DBTypes.ORACLE)) {
						if (StringUtils.isNotBlank(frameworkTextReport
								.getOrderByCluase())) {
							intermittentSQL = intermittentSQL + " ORDER BY "
									+ frameworkTextReport.getOrderByCluase();
							intermittentSQL = "SELECT * FROM  ( SELECT  a.*, ROWNUM RowNumber FROM ( "
									+ intermittentSQL
									+ " ) a  WHERE ROWNUM < "
									+ endRow
									+ " ) WHERE RowNumber >= "
									+ offset;
						} else {
							intermittentSQL = "SELECT * FROM  ( SELECT  a.*, ROWNUM RowNumber FROM ( "
									+ intermittentSQL
									+ " ) a  WHERE ROWNUM < "
									+ endRow
									+ " ) WHERE RowNumber >= " + offset;
						}

						finalSQL = intermittentSQL;

						finalSQL = finalSQL.replaceAll("`", "");
					} else if (StringUtils.equalsIgnoreCase(
							dbMode,
							SystemConstants.DBTypes.SQLSERVER)) {
						intermittentSQL = intermittentSQL.replaceFirst(
								"SELECT",
								"SELECT ROW_NUMBER() OVER ( ORDER BY "
										+ primaryKey + " " + sord
										+ " ) AS RowNumber,");

						finalSQL = "SELECT RowConstrainedResult.* FROM ("
								+ intermittentSQL
								+ " )  RowConstrainedResult WHERE RowNumber > "
								+ offset + " AND RowNumber <= " + endRow
								+ " ORDER BY RowNumber";

						finalSQL = finalSQL.replaceAll("`", "\"");
					} else if (StringUtils.equalsIgnoreCase(
							dbMode,
							SystemConstants.DBTypes.MYSQL)) {
						if (StringUtils.isNotBlank(frameworkTextReport
								.getOrderByCluase())) {
							finalSQL = intermittentSQL + " ORDER BY "
									+ frameworkTextReport.getOrderByCluase()
									+ " LIMIT " + offset + " ," + endRow;
						} else {
							finalSQL = intermittentSQL + " LIMIT " + offset
									+ " ," + endRow;
						}
					}

					databaseResult = loadResult(finalSQL, datasourceName);

					convertColumnMetaDataToReportMetaData(databaseResult,
							frameworkTextReport);

				}

				// Load Rico Table Once
				frameworkTextReport.getRicoTable();
				// Store in Cache
				// FrameworkMetaDataCache.getInstance().storeReport(id,
				// frameworkTextReport);
			}
		}
		return frameworkTextReport;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.northalley.framework.service.PlatformService#loadReportData(com.
	 * northalley.framework.dataobject.FrameworkTextReport)
	 */
	public DatabaseResult loadReportData(FrameworkTextReport frameworkTextReport) {
		// If GetTotal is true then return max rows for query
		int totalRows = -1;

		String datasourceName = getDataSourceName(frameworkTextReport);
		StringBuffer queryToCount = new StringBuffer();
		StringBuffer queryToExecute = new StringBuffer();
		DatabaseResult databaseResult = null;
		FrameworkApplication app = SystemContext.getInstance().getUserContext()
				.getFrameworkUser().getListOfApplications().get(0);

		String sql = "";

		if (StringUtils.equalsIgnoreCase(frameworkTextReport
				.getFrameworkTable().getTableType(),
				SystemConstants.EntityTypes.TABLE_DBOBJECT)) {
			queryToExecute
					.append("SELECT * FROM ")
					.append(frameworkTextReport.getFrameworkTable()
							.getTableSchema())
					.append(".")
					.append(frameworkTextReport.getFrameworkTable()
							.getTableName()).append(" WHERE 1=1 ");

		} else {
			queryToExecute.append(frameworkTextReport.getFrameworkTable()
					.getTableSQL());
			if (!StringUtils.containsIgnoreCase(frameworkTextReport
					.getFrameworkTable().getTableSQL(), "where ")) {
				queryToExecute.append(" where 1=1 ");
			}
		}

		appendFilters(frameworkTextReport, queryToExecute);

		/**
		 * Find total Number of records for this query
		 */
		if (!StringUtils.containsIgnoreCase(datasourceName, "jdbcTemplate")) {
			if (StringUtils.equalsIgnoreCase(app.getDatasourceType(),
					SystemConstants.DBTypes.ORACLE)) {
				queryToCount.append("SELECT count(*) FROM (")
						.append(queryToExecute.toString().replaceAll("`", ""))
						.append(") A");
			} else if (StringUtils.equalsIgnoreCase(app.getDatasourceType(),
					SystemConstants.DBTypes.MYSQL)) {
				queryToCount.append("SELECT count(*) FROM (")
						.append(queryToExecute.toString().replaceAll("`", ""))
						.append(") A");
			}
		} else {
			queryToCount.append("SELECT count(*) FROM (")
					.append(queryToExecute.toString().replaceAll("`", ""))
					.append(") A");
		}

		totalRows = getPlatformDAO().queryForInt(queryToCount.toString(),
				datasourceName, new ArrayList());
		queryToCount = null;

		String finalSQL = "";
		String primaryKey = frameworkTextReport.getFrameworkTable()
				.getPrimaryKeyColumn();
		String sord = "ASC";

		String offset = "OFFSET_MARKER";
		String endRow = "ENDROW_MARKER";
		int offsetNum = Integer.parseInt(getRequestParamter("offset"));
		int rowCount = Integer.parseInt(getRequestParamter("page_size"));
		// int endRow = 999999999;

		/**
		 * Surround SQL with a outer SQL
		 */
		String intermittentSQL = "SELECT X.* FROM ( "
				+ queryToExecute.toString() + " ) X ";

		String dbMode = "MYSQL";

		if (StringUtils.equals(getDataSourceName(frameworkTextReport), "frameworkJdbcTemplate")) {
			dbMode = dbType;
		} else {
			dbMode = app.getDatasourceType();
		}

		if (StringUtils.equalsIgnoreCase(dbMode,
				SystemConstants.DBTypes.ORACLE)) {
			if (StringUtils.isNotBlank(frameworkTextReport.getOrderByCluase())) {
				intermittentSQL = intermittentSQL + " ORDER BY "
						+ frameworkTextReport.getOrderByCluase();
				intermittentSQL = "SELECT * FROM  ( SELECT  a.*, ROWNUM RowNumber FROM ( "
						+ intermittentSQL
						+ " ) a  WHERE ROWNUM < "
						+ endRow
						+ " ) WHERE RowNumber >= " + offset;
			} else {
				intermittentSQL = "SELECT * FROM  ( SELECT  a.*, ROWNUM RowNumber FROM ( "
						+ sql
						+ " ) a  WHERE ROWNUM < "
						+ endRow
						+ " ) WHERE RowNumber >= " + offset;
			}

			finalSQL = intermittentSQL;

			finalSQL = finalSQL.replaceAll("`", "");
		} else if (StringUtils.equalsIgnoreCase(dbMode,
				SystemConstants.DBTypes.SQLSERVER)) {
			intermittentSQL = intermittentSQL.replaceFirst("SELECT",
					"SELECT ROW_NUMBER() OVER ( ORDER BY " + primaryKey + " "
							+ sord + " ) AS RowNumber,");

			finalSQL = "SELECT RowConstrainedResult.* FROM (" + intermittentSQL
					+ " )  RowConstrainedResult WHERE RowNumber > " + offset
					+ " AND RowNumber <= " + endRow + " ORDER BY RowNumber";

			finalSQL = finalSQL.replaceAll("`", "\"");
		} else if (StringUtils.equalsIgnoreCase(dbMode,
				SystemConstants.DBTypes.MYSQL)) {
			if (StringUtils.isNotBlank(frameworkTextReport.getOrderByCluase())) {
				finalSQL = intermittentSQL + " ORDER BY "
						+ frameworkTextReport.getOrderByCluase() + " LIMIT "
						+ offset + " ," + endRow;
			} else {
				finalSQL = intermittentSQL + " LIMIT " + offset + " ," + endRow;
			}
		}

		queryToExecute.setLength(0);
		queryToExecute.append(finalSQL);

		String sqlAfterEvaluation = FreeMarkerEngine.getInstance()
				.evaluateString(queryToExecute.toString());

		StringBuffer exportSQL = new StringBuffer(sqlAfterEvaluation
				.replaceAll("OFFSET_MARKER", "0").replaceAll("ENDROW_MARKER",
						"99999999"));
		/**
		 * Store report
		 */
		SystemContext
				.getInstance()
				.getSqlExportMap()
				.put(frameworkTextReport.getReportId(),
						datasourceName + "___" + exportSQL.toString());

		databaseResult = loadResult(
				sqlAfterEvaluation.replaceAll("OFFSET_MARKER", offsetNum + "")
						.replaceAll("ENDROW_MARKER", offsetNum + rowCount + ""),
				datasourceName);

		if (totalRows != -1) {
			databaseResult.setTotalRows(totalRows);
		}

		return databaseResult;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.northalley.framework.service.PlatformService#loadReportData(com.
	 * northalley.framework.dataobject.FrameworkTextReport)
	 */
	public DatabaseResult loadReportDataFromSQL(String reportSQL,
			FrameworkTextReport frameworkTextReport) {
		// If GetTotal is true then return max rows for query
		int totalRows = -1;
		String datasourceName = "jdbcTemplate";

		// Now Create Query Out of it and Load Data
		StringBuffer queryToCount = new StringBuffer();
		StringBuffer queryToExecute = new StringBuffer();
		DatabaseResult databaseResult = null;
		FrameworkApplication app = SystemContext.getInstance().getUserContext()
				.getFrameworkUser().getListOfApplications().get(0);

		String sql = "";

		queryToExecute.append(reportSQL);

		if (!StringUtils
				.containsIgnoreCase(queryToExecute.toString(), "where ")) {
			queryToExecute.append(" where 1=1 ");
		}

		appendFilters(frameworkTextReport, queryToExecute);

		String dbMode = "MYSQL";

		if (StringUtils.equals(getDataSourceName(frameworkTextReport), "frameworkJdbcTemplate")) {
			dbMode = dbType;
		} else {
			dbMode = app.getDatasourceType();
		}

		/**
		 * Find total Number of records for this query
		 */
		if (StringUtils.equalsIgnoreCase(dbMode,
				SystemConstants.DBTypes.ORACLE)) {
			queryToCount.append("SELECT count(*) FROM (")
					.append(queryToExecute.toString().replaceAll("`", ""))
					.append(") A");
		} else if (StringUtils.equalsIgnoreCase(dbMode,
				SystemConstants.DBTypes.MYSQL)) {
			queryToCount.append("SELECT count(*) FROM (")
					.append(queryToExecute.toString().replaceAll("`", ""))
					.append(") A");
		}

		totalRows = getPlatformDAO().queryForInt(queryToCount.toString(),
				datasourceName, new ArrayList());
		queryToCount = null;

		String finalSQL = "";
		String primaryKey = frameworkTextReport.getFrameworkTable()
				.getPrimaryKeyColumn();
		String sord = "ASC";

		String offset = "OFFSET_MARKER";
		String endRow = "ENDROW_MARKER";
		int offsetNum = Integer.parseInt(getRequestParamter("offset"));
		int rowCount = Integer.parseInt(getRequestParamter("page_size"));
		// int endRow = 999999999;

		/**
		 * Surround SQL with a outer SQL
		 */
		String intermittentSQL = "SELECT X.* FROM ( "
				+ queryToExecute.toString() + " ) X ";

		if (StringUtils.equalsIgnoreCase(dbMode,
				SystemConstants.DBTypes.ORACLE)) {
			// intermittentSQL = intermittentSQL.replaceFirst("SELECT",
			// "SELECT ROW_NUMBER() OVER ( ORDER BY " + primaryKey + " " + sord
			// + " ) AS RowNumber,");

			// finalSQL = "SELECT RowConstrainedResult.* FROM (" +
			// intermittentSQL
			// + " )  RowConstrainedResult WHERE RowNumber > " + offset +
			// " AND RowNumber <= "
			// + endRow + " ORDER BY RowNumber";

			if (StringUtils.isNotBlank(frameworkTextReport.getOrderByCluase())) {
				intermittentSQL = intermittentSQL + " ORDER BY "
						+ frameworkTextReport.getOrderByCluase();
				intermittentSQL = "SELECT * FROM  ( SELECT  a.*, ROWNUM RowNumber FROM ( "
						+ intermittentSQL
						+ " ) a  WHERE ROWNUM < "
						+ endRow
						+ " ) WHERE RowNumber >= " + offset;
			} else {
				intermittentSQL = "SELECT * FROM  ( SELECT  a.*, ROWNUM RowNumber FROM ( "
						+ intermittentSQL
						+ " ) a  WHERE ROWNUM < "
						+ endRow
						+ " ) WHERE RowNumber >= " + offset;
			}

			finalSQL = intermittentSQL;

			finalSQL = finalSQL.replaceAll("`", "");
		} else if (StringUtils.equalsIgnoreCase(dbMode,
				SystemConstants.DBTypes.SQLSERVER)) {
			intermittentSQL = intermittentSQL.replaceFirst("SELECT",
					"SELECT ROW_NUMBER() OVER ( ORDER BY " + primaryKey + " "
							+ sord + " ) AS RowNumber,");

			finalSQL = "SELECT RowConstrainedResult.* FROM (" + intermittentSQL
					+ " )  RowConstrainedResult WHERE RowNumber > " + offset
					+ " AND RowNumber <= " + endRow + " ORDER BY RowNumber";

			finalSQL = finalSQL.replaceAll("`", "\"");
		} else if (StringUtils.equalsIgnoreCase(dbMode,
				SystemConstants.DBTypes.MYSQL)) {
			if (StringUtils.isNotBlank(frameworkTextReport.getOrderByCluase())) {
				finalSQL = intermittentSQL + " ORDER BY "
						+ frameworkTextReport.getOrderByCluase() + " LIMIT "
						+ offset + " ," + endRow;
			} else {
				finalSQL = intermittentSQL + " LIMIT " + offset + " ," + endRow;
			}
		}

		queryToExecute.setLength(0);
		queryToExecute.append(finalSQL);

		String sqlAfterEvaluation = FreeMarkerEngine.getInstance()
				.evaluateString(queryToExecute.toString());

		StringBuffer exportSQL = new StringBuffer(sqlAfterEvaluation
				.replaceAll("OFFSET_MARKER", "0").replaceAll("ENDROW_MARKER",
						"99999999"));
		/**
		 * Store report
		 */
		SystemContext
				.getInstance()
				.getSqlExportMap()
				.put(frameworkTextReport.getReportId(),
						datasourceName + "___" + exportSQL.toString());

		databaseResult = loadResult(
				sqlAfterEvaluation.replaceAll("OFFSET_MARKER", offsetNum + "")
						.replaceAll("ENDROW_MARKER", offsetNum + rowCount + ""),
				datasourceName);

		if (totalRows != -1) {
			databaseResult.setTotalRows(totalRows);
		}

		return databaseResult;
	}

	/**
	 * 
	 * This has logic to Append Filters From UI
	 * 
	 * @param reportComponent
	 * @param queryToExecute
	 */
	private void appendFilters(FrameworkTextReport reportComponent, StringBuffer queryToExecute) {
		// Add Filters to the Query
		for (RequestCondition mapObject : reportComponent.getConditions()) {
			if (StringUtils.startsWithIgnoreCase(mapObject.getKey(), "F_DATETIME_")) {
				// This date value in the following format to we have to parse
				// it
				// 10-Jan-2013 02:52:39
				String dateString = mapObject.getValue();
				Date dateValue = null;
				if (StringUtils.isNotBlank(dateString)) {
					try {
						dateValue = DateUtils.getInstance().getDate(dateString);

						dateString = DateUtils.getInstance().getDateString(dateValue, "yyyy-MM-dd hh:mm:ss");

					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					String columnName = mapObject.getKey().replaceAll("F_DATE_", "");

					// Now Append Date Value to query
					queryToExecute.append(" AND ").append(columnName).append(" LIKE '").append(dateString).append("' ");
				}

			} else if (StringUtils.startsWithIgnoreCase(mapObject.getKey(), "F_DATE_")) {
				// This date value in the following format to we have to parse
				// it
				// 10-Jan-2013 02:52:39
				String dateString = mapObject.getValue();
				Date dateValue = null;
				if (StringUtils.isNotBlank(dateString)) {
					try {
						dateValue = DateUtils.getInstance().getDate(dateString, "dd-MMM-yyyy");

						dateString = DateUtils.getInstance().getDateString(dateValue, "yyyy-MM-dd");

					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					String columnName = mapObject.getKey().replaceAll("F_DATE_", "");

					// Now Append Date Value to query
					queryToExecute.append(" AND ").append(columnName).append(" LIKE '").append(dateString).append("' ");
				}

			} else {
				/*
				 * queryToExecute.append(" AND ").append(mapObject.getKey())
				 * .append(" LIKE '%").append(mapObject.getValue())
				 * .append("%' ");
				 */
				if (StringUtils.isNotBlank(mapObject.getValue()) && StringUtils.isNotBlank(mapObject.getCondition())
						&& StringUtils.equalsIgnoreCase(mapObject.getCondition(), ConditionalConstants.EQUALS)) {
					queryToExecute.append(" AND ").append(mapObject.getKey()).append(" = '").append(
							mapObject.getValue()).append("' ");
				} else if (StringUtils.isNotBlank(mapObject.getValue())
						&& StringUtils.isNotBlank(mapObject.getCondition())
						&& StringUtils.equalsIgnoreCase(mapObject.getCondition(), ConditionalConstants.ENDS_WITH)) {
					queryToExecute.append(" AND ").append(mapObject.getKey()).append(" LIKE '%").append(
							mapObject.getValue()).append("' ");
				} else if (StringUtils.isNotBlank(mapObject.getValue())
						&& StringUtils.isNotBlank(mapObject.getCondition())
						&& StringUtils.equalsIgnoreCase(mapObject.getCondition(), ConditionalConstants.STARTS_WITH)) {
					queryToExecute.append(" AND ").append(mapObject.getKey()).append(" LIKE '").append(
							mapObject.getValue()).append("%' ");
				} else if (StringUtils.isNotBlank(mapObject.getValue())
						&& StringUtils.isNotBlank(mapObject.getCondition())
						&& StringUtils.equalsIgnoreCase(mapObject.getCondition(), ConditionalConstants.CONTAINS)) {
					queryToExecute.append(" AND ").append(mapObject.getKey()).append(" LIKE '%").append(
							mapObject.getValue()).append("%' ");
				} else {
					queryToExecute.append(" AND ").append(mapObject.getKey()).append(" LIKE '%").append(
							mapObject.getValue()).append("%' ");
				}
			}
		}
	}

	/**
	 * This method creates ReportColumns based on Column Metadata. This is used
	 * when ever we dont find any configuration for report columns in Database
	 * 
	 * @param databaseResult
	 * @param reportObject
	 */
	private void convertColumnMetaDataToReportMetaData(DatabaseResult databaseResult, FrameworkTextReport reportObject) {
		int order = 0;
		for (ColumnMetadata columnMetadata : databaseResult.getMetadata().getColumnsList()) {
			if (isSystemColumn(columnMetadata.getColumnName())) {
				continue;
			}

			if (StringUtils.equalsIgnoreCase(columnMetadata.getColumnName(), "RowNumber")) {
				continue;
			}

			FrameworkReportColumn reportColumn = new FrameworkReportColumn();
			reportColumn.setColumnName(columnMetadata.getColumnName());
			reportColumn.setColumnLabel(columnMetadata.getColumnLabel());
			reportColumn.setColumnType(columnMetadata.getColumnTypeName());
			reportColumn.setActive(true);
			reportColumn.setColumnDescription(columnMetadata.getColumnName());
			reportColumn.setColumnId(columnMetadata.getColumnName());
			reportColumn.setColumnOrder(order);
			reportColumn.setReportId(reportObject.getReportId());
			reportColumn.setDisplayWidth(columnMetadata.getColumnDisplaySize());
			reportColumn.setNullable(columnMetadata.isNullable());
			reportColumn.setPrecision(columnMetadata.getPrecision());
			reportColumn.setScale(columnMetadata.getScale());

			if (!columnMetadata.isNullable()) {
				reportColumn.setColumnLabel(columnMetadata.getColumnLabel() + "*");
			}

			reportObject.getColumns().add(reportColumn);
			order = order + 1;
		}
	}

	/**
	 * * (non-Javadoc)
	 * 
	 * @see com.northalley.framework.service.PlatformService#loadTreeMenu()
	 */
	public List<FrameworkMenu> loadTreeMenu() {
		String identifierRole = SystemContext.getInstance().getUserContext().getRole();
		String identifier = SystemContext.getInstance().getUserContext().getIdentifier();

		String queryString = "";
		if (!StringUtils.equalsIgnoreCase(identifierRole, "ADMIN")) {
			queryString = " AND IDENTIFIER_ROLE IN ('" + identifierRole.toUpperCase() + "','ALL') AND IDENTIFIER IN ('"
					+ identifier.toUpperCase() + "','ALL') ";
		} else {
			queryString = " AND IDENTIFIER_ROLE IN ('ADMIN','ALL') AND IDENTIFIER IN ('" + identifier.toUpperCase()
					+ "','ALL') ";
		}

		String parentMenuSQL = "SELECT * FROM FRM_MENU WHERE MENU_TYPE = 'TREE' AND PARENT_MENU_ID = '-1' " + queryString
				+ "ORDER BY MENU_ORDER";
		List<FrameworkMenu> parentList = getPlatformDAO().loadMenu(parentMenuSQL);
		for (FrameworkMenu parent : parentList) {
			String childMenuSQL = "SELECT * FROM FRM_MENU WHERE MENU_TYPE = 'TREE' " + queryString
					+ " AND PARENT_MENU_ID = '" + parent.getMenuId() + "' ORDER BY MENU_ORDER";
			parent.setChildren(getPlatformDAO().loadMenu(childMenuSQL));
		}

		return parentList;
	}

	/**
	 * * (non-Javadoc)
	 * 
	 * @see com.northalley.framework.service.PlatformService#insertRecordForReport (com.northalley.framework.dataobject.FrameworkTextReport)
	 */
	public void insertRecordForReport(FrameworkTextReport reportObject) {
		StringBuffer insertSQL = new StringBuffer();
		insertSQL.append("INSERT INTO ").append(reportObject.getFrameworkTable().getTableSchema()).append(".").append(
				reportObject.getFrameworkTable().getTableName() + " (");

		List paramConditions = new ArrayList();
		List paramNames = new ArrayList();
		String datasourceName = getDataSourceName(reportObject);
		for (FrameworkReportColumn reportColumn : reportObject.getColumns()) {
			String requestParamValue = getRequestParamterWithNoEvaluation(reportColumn.getColumnName());

			/**
			 * System Columns are generated by code
			 */

			/**
			 * StringUtils.equalsIgnoreCase(reportColumn.getColumnName(),
			 * reportObject.getFrameworkTable().getPrimaryKeyColumn()) ||
			 */
			if (isSystemColumn(reportColumn.getColumnName())) {
				continue;
			}
			if (!StringUtils.isBlank(requestParamValue)) {
				insertSQL.append("`").append(reportColumn.getColumnName()).append("`").append(",");

				if (StringUtils.equalsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.TINYINT)
						|| StringUtils.equalsIgnoreCase(reportColumn.getColumnType(),
								SystemConstants.ColumnTypes.BOOLEAN)) {
					if (StringUtils.equalsIgnoreCase(requestParamValue, "on")) {
						paramConditions.add(new Boolean(true));
					} else {
						paramConditions.add(new Boolean(false));
					}
					paramNames.add(reportColumn.getColumnName());

				} else if (StringUtils.containsIgnoreCase(reportColumn.getColumnType(),
						SystemConstants.ColumnTypes.NUMBER)
						|| StringUtils.containsIgnoreCase(reportColumn.getColumnType(),
								SystemConstants.ColumnTypes.INTEGER)) {
					Double numberObject = null;

					if (reportColumn.isNullable() && StringUtils.isBlank(requestParamValue)) {
						continue;
					}

					String[] numbers = StringUtils.split(requestParamValue, ".");
					if (numbers.length > 1) {
						if (numbers[1].length() > reportColumn.getScale()) {
							logger.debug("Invalid number entered for:" + reportColumn.getColumnName() + ".Max "
									+ reportColumn.getScale() + " decimal Values allowed..:");
							SystemContext.getInstance().getUniqueMessage().set(
									"Invalid number entered for:" + reportColumn.getColumnName() + ".Max "
											+ reportColumn.getScale() + " decimal Values allowed..:");
							SystemContext.getInstance().getMessages().add(
									"Invalid number entered for:" + reportColumn.getColumnName() + ".Max "
											+ reportColumn.getScale() + " decimal Values allowed..:");
							return;
						}
					}

					try {
						numberObject = Double.parseDouble(requestParamValue);
					} catch (Exception e) {
						logger.debug("Invalid number entered for:" + reportColumn.getColumnName() + "..:", e);
						SystemContext.getInstance().getUniqueMessage().set(
								"Invalid number entered for:" + reportColumn.getColumnName());
						SystemContext.getInstance().getMessages().add(
								"Invalid number entered for:" + reportColumn.getColumnName());
						return;
					}
					paramConditions.add(numberObject);
					paramNames.add(reportColumn.getColumnName());
					continue;

				} else if (StringUtils.equalsIgnoreCase(
						reportColumn.getColumnType(),
						SystemConstants.ColumnTypes.DATETIME)
						|| StringUtils.equalsIgnoreCase(
								reportColumn.getColumnType(),
								SystemConstants.ColumnTypes.DATE)
						|| StringUtils.equalsIgnoreCase(
								reportColumn.getColumnType(),
								SystemConstants.ColumnTypes.TIME)
						|| StringUtils.equalsIgnoreCase(
								reportColumn.getColumnType(),
								SystemConstants.ColumnTypes.TIMESTAMP)) {
					// 2012-11-11 00:00:00
					Date dateObject = getDateObject(requestParamValue,
							"yyyy-MM-dd hh:mm:ss");
					if (dateObject == null) {
						dateObject = getDateObject(requestParamValue,
								"yyyy-MM-dd");
					}

					if (StringUtils.equalsIgnoreCase(
							reportColumn.getColumnType(),
							SystemConstants.ColumnTypes.TIMESTAMP)) {
						TimeZone timeZone = TimeZone.getDefault();
						Calendar timeWithZone = Calendar.getInstance(timeZone);
						timeWithZone.setTime(dateObject);

						paramConditions.add(new Timestamp(timeWithZone.getTimeInMillis()));
					} else {
						paramConditions.add(dateObject);
					}
					paramNames.add(reportColumn.getColumnName());
					continue;
				} else {
					int entryLength = requestParamValue.length();
					if (entryLength > reportColumn.getDisplayWidth()) {
						logger.debug("Entry length exceeded for: " + reportColumn.getColumnName() + ". Max value is:"
								+ reportColumn.getDisplayWidth());
						// String errorMessage = e.getCause().getMessage();
						SystemContext.getInstance().getUniqueMessage().set(
								"Entry length exceeded for: " + reportColumn.getColumnName() + ". Max value is:"
										+ reportColumn.getDisplayWidth());
						SystemContext.getInstance().getMessages().add(
								"Entry length exceeded for: " + reportColumn.getColumnName() + ". Max value is:"
										+ reportColumn.getDisplayWidth());
						return;
					}
					paramConditions.add(requestParamValue);
					paramNames.add(reportColumn.getColumnName());
				}
			}
		}

		if (StringUtils.startsWithIgnoreCase(reportObject.getTableId(), SystemConstants.FRAMEWORK_TABLE_PREFIX)) {
			insertSystemParams(insertSQL);
			insertSQL.append(") VALUES (");
		} else {
			insertSQL = insertSQL.deleteCharAt(insertSQL.length() - 1);
			insertSQL.append(") VALUES (");
		}

		for (Object paramValue : paramConditions) {
			insertSQL.append("?,");
		}

		if (StringUtils.startsWithIgnoreCase(reportObject.getTableId(), SystemConstants.FRAMEWORK_TABLE_PREFIX)) {
			insertSystemParamValues(paramConditions, insertSQL);
		} else {
			insertSQL = insertSQL.deleteCharAt(insertSQL.length() - 1);
		}
		insertSQL.append(")");

		System.out.println(insertSQL.toString());
		FrameworkApplication app = SystemContext.getInstance().getUserContext().getFrameworkUser()
				.getListOfApplications().get(0);

		DBUpdateStatement dbUpdateStatement = new DBUpdateStatement();
		dbUpdateStatement.setTableName(reportObject.getFrameworkTable().getTableName());
		dbUpdateStatement.setArguments(paramConditions);
		dbUpdateStatement.setColumnNames(paramNames);
		dbUpdateStatement.setDatasourceName(datasourceName);
		dbUpdateStatement.setApplication(app);

		if (StringUtils.equalsIgnoreCase(app.getDatasourceType(), SystemConstants.DBTypes.ORACLE)) {
			dbUpdateStatement.setUpdateStatement(insertSQL.toString().replaceAll("`", ""));
		} else if (StringUtils.equalsIgnoreCase(app.getDatasourceType(), SystemConstants.DBTypes.SQLSERVER)) {
			dbUpdateStatement.setUpdateStatement(insertSQL.toString().replaceAll("`", "\""));
		} else {
			dbUpdateStatement.setUpdateStatement(insertSQL.toString());
		}

		getPlatformDAO().addNewTransactionForTable(dbUpdateStatement);
		SystemContext.getInstance().getApprovalMap().put(reportObject.getFrameworkTable().getTableName(),
				dbUpdateStatement);

	}

	/**
	 * @param reportObject
	 */
	public void updateRecordForReport(FrameworkTextReport reportObject) {
		StringBuffer updateSQL = new StringBuffer();
		String datasourceName = getDataSourceName(reportObject);

		updateSQL.append("UPDATE " + reportObject.getFrameworkTable().getTableSchema() + "."
				+ reportObject.getFrameworkTable().getTableName() + " SET ");

		List paramConditions = new ArrayList();
		List paramNames = new ArrayList();
		for (FrameworkReportColumn reportColumn : reportObject.getColumns()) {
			String requestParamValue = getRequestParamterWithNoEvaluation(reportColumn.getColumnName());

			/**
			 * Primary key is auto incremented by assumption
			 */
			String[] primaryColumnNames = reportObject.getFrameworkTable().getPrimaryKeyColumn().split(",");
			List<String> primaryColumns = new ArrayList<String>();
			for (String columnName : primaryColumnNames) {
				primaryColumns.add(columnName);
			}

			if (primaryColumns.contains(reportColumn.getColumnName()) || isSystemColumn(reportColumn.getColumnName())) {
				continue;
			}

			if (StringUtils.equalsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.TINYINT)
					|| StringUtils.equalsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.BOOLEAN)) {
				if (StringUtils.equalsIgnoreCase(requestParamValue, "on")) {
					requestParamValue = "1";
				} else {
					requestParamValue = "0";
				}
			}

			if (StringUtils.containsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.NUMBER)
					|| StringUtils
							.containsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.INTEGER)) {
				Double numberObject = null;

				if (reportColumn.isNullable() && StringUtils.isBlank(requestParamValue)) {
					continue;
				}

				String[] numbers = StringUtils.split(requestParamValue, ".");
				if (numbers.length > 1) {
					if (numbers[1].length() > reportColumn.getScale()) {
						logger.debug("Invalid number entered for:" + reportColumn.getColumnName() + ".Max "
								+ reportColumn.getScale() + " decimal Values allowed..:");
						SystemContext.getInstance().getUniqueMessage().set(
								"Invalid number entered for:" + reportColumn.getColumnName() + ".Max "
										+ reportColumn.getScale() + " decimal Values allowed..:");
						SystemContext.getInstance().getMessages().add(
								"Invalid number entered for:" + reportColumn.getColumnName() + ".Max "
										+ reportColumn.getScale() + " decimal Values allowed..:");
						return;
					}
				}

				try {
					numberObject = Double.parseDouble(requestParamValue);
				} catch (Exception e) {
					logger.debug("Invalid number entered for" + reportColumn.getColumnName() + "..:", e);
					// String errorMessage = e.getCause().getMessage();
					SystemContext.getInstance().getUniqueMessage().set(
							"Invalid number entered for:" + reportColumn.getColumnName());
					SystemContext.getInstance().getMessages().add(
							"Invalid number entered for:" + reportColumn.getColumnName());
					return;
				}
				updateSQL.append("`").append(reportColumn.getColumnName()).append("`").append("= ?,");
				paramConditions.add(numberObject);
				paramNames.add(reportColumn.getColumnName());
				continue;
			}

			if (StringUtils.equalsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.DATETIME)
					|| StringUtils.equalsIgnoreCase(
							reportColumn.getColumnType(),
							SystemConstants.ColumnTypes.DATE)
					|| StringUtils.equalsIgnoreCase(
							reportColumn.getColumnType(),
							SystemConstants.ColumnTypes.TIME)
					|| StringUtils.equalsIgnoreCase(
							reportColumn.getColumnType(),
							SystemConstants.ColumnTypes.TIMESTAMP)) {
				// 2012-11-11 00:00:00
				Date dateObject = getDateObject(requestParamValue,
						"yyyy-MM-dd hh:mm:ss");
				if (dateObject == null) {
					dateObject = getDateObject(requestParamValue, "yyyy-MM-dd");
				}
				updateSQL.append("`").append(reportColumn.getColumnName())
						.append("`").append("= ?,");

				if (StringUtils.equalsIgnoreCase(
						reportColumn.getColumnType(),
						SystemConstants.ColumnTypes.TIMESTAMP)) {
					TimeZone timeZone = TimeZone.getDefault();
					Calendar timeWithZone = Calendar.getInstance(timeZone);
					timeWithZone.setTime(dateObject);

					paramConditions.add(new Timestamp(timeWithZone.getTimeInMillis()));
				} else {
					paramConditions.add(dateObject);
				}
				paramNames.add(reportColumn.getColumnName());
				continue;
			}

			if (!StringUtils.isBlank(requestParamValue)) {
				int entryLength = requestParamValue.length();
				if (entryLength > reportColumn.getDisplayWidth()) {
					logger.debug("Entry length exceeded for: " + reportColumn.getColumnName() + ". Max value is:"
							+ reportColumn.getDisplayWidth());
					// String errorMessage = e.getCause().getMessage();
					SystemContext.getInstance().getUniqueMessage().set(
							"Entry length exceeded for: " + reportColumn.getColumnName() + ". Max value is:"
									+ reportColumn.getDisplayWidth());
					SystemContext.getInstance().getMessages().add(
							"Entry length exceeded for: " + reportColumn.getColumnName() + ". Max value is:"
									+ reportColumn.getDisplayWidth());
					return;
				}
				updateSQL.append("`").append(reportColumn.getColumnName()).append("`").append("= ?,");
				paramConditions.add(requestParamValue);
				paramNames.add(reportColumn.getColumnName());
			}
		}
		updateSQL.deleteCharAt(updateSQL.length() - 1);
		updateSQL.append(" WHERE ");

		/**
		 * Now add Primary keys
		 */
		String[] primaryColumnNames = reportObject.getFrameworkTable().getPrimaryKeyColumn().split(",");
		List<String> primaryColumns = new ArrayList<String>();
		boolean isFirstColumn = true;
		for (String columnName : primaryColumnNames) {
			if (isFirstColumn) {
				isFirstColumn = false;
				updateSQL.append("`").append(columnName).append("`=?");
			} else {
				updateSQL.append(" and `").append(columnName).append("`=?");
			}

			paramNames.add(columnName);

			String requestParamValue = getRequestParamterWithNoEvaluation(columnName);
			if (StringUtils.equalsIgnoreCase(reportObject.getColumnByName(columnName).getColumnType(),
					SystemConstants.ColumnTypes.DATETIME)
					|| StringUtils.equalsIgnoreCase(reportObject.getColumnByName(columnName).getColumnType(),
							SystemConstants.ColumnTypes.DATE)
					|| StringUtils.equalsIgnoreCase(reportObject.getColumnByName(columnName).getColumnType(),
							SystemConstants.ColumnTypes.TIME)) {
				// 2012-11-11 00:00:00
				Date dateObject = getDateObject(requestParamValue, "yyyy-MM-dd hh:mm:ss");
				if (dateObject == null) {
					dateObject = getDateObject(requestParamValue, "yyyy-MM-dd");
				}
				paramConditions.add(dateObject);
				continue;
			} else if (StringUtils.equalsIgnoreCase(reportObject.getColumnByName(columnName).getColumnType(),
					SystemConstants.ColumnTypes.INTEGER)) {
				// 2012-11-11 00:00:00
				Integer intObject = Integer.parseInt(requestParamValue);
				paramConditions.add(intObject);
				continue;
			} else {
				paramConditions.add(requestParamValue);
			}

		}

		System.out.println(updateSQL.toString());

		FrameworkApplication app = SystemContext.getInstance().getUserContext().getFrameworkUser()
				.getListOfApplications().get(0);

		DBUpdateStatement dbUpdateStatement = new DBUpdateStatement();
		dbUpdateStatement.setTableName(reportObject.getFrameworkTable().getTableName());
		dbUpdateStatement.setArguments(paramConditions);
		dbUpdateStatement.setColumnNames(paramNames);
		dbUpdateStatement.setDatasourceName(datasourceName);
		dbUpdateStatement.setApplication(app);

		if (StringUtils.equalsIgnoreCase(app.getDatasourceType(), SystemConstants.DBTypes.ORACLE)) {
			dbUpdateStatement.setUpdateStatement(updateSQL.toString().replaceAll("`", ""));
		} else if (StringUtils.equalsIgnoreCase(app.getDatasourceType(), SystemConstants.DBTypes.SQLSERVER)) {
			dbUpdateStatement.setUpdateStatement(updateSQL.toString().replaceAll("`", "\""));
		} else {
			dbUpdateStatement.setUpdateStatement(updateSQL.toString());
		}

		getPlatformDAO().addNewTransactionForTable(dbUpdateStatement);

		SystemContext.getInstance().getApprovalMap().put(reportObject.getFrameworkTable().getTableName(),
				dbUpdateStatement);
	}

	/**
	 * @param reportObject
	 */
	public void deleteRecordInReport(FrameworkTextReport reportObject) {
		StringBuffer deleteSQL = new StringBuffer();
		List paramConditions = new ArrayList();
		List paramNames = new ArrayList();
		String datasourceName = getDataSourceName(reportObject);
		deleteSQL.append("DELETE FROM ").append(reportObject.getFrameworkTable().getTableSchema()).append(".").append(
				reportObject.getFrameworkTable().getTableName()).append(" WHERE ");

		/**
		 * Primary key is auto incremented by assumption
		 */
		String[] primaryColumnNames = reportObject.getFrameworkTable().getPrimaryKeyColumn().split(",");
		List<String> primaryColumns = new ArrayList<String>();
		for (String columnName : primaryColumnNames) {
			primaryColumns.add(columnName);
		}

		/**
		 * Now add Primary keys
		 */
		boolean isFirstColumn = true;
		for (int index = 0; index < reportObject.getColumns().size(); index++) {
			FrameworkReportColumn reportColumn = reportObject.getColumns().get(index);
			String requestParamValue = getRequestParamterWithNoEvaluation("_k" + index);

			if (!primaryColumns.contains(reportColumn.getColumnName())) {
				continue;
			}

			if (StringUtils.equalsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.DATETIME)
					|| StringUtils.equalsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.DATE)
					|| StringUtils.equalsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.TIME)) {
				// 2012-11-11 00:00:00
				Date dateObject = getDateObject(requestParamValue, "yyyy-MM-dd hh:mm:ss");
				if (dateObject == null) {
					dateObject = getDateObject(requestParamValue, "yyyy-MM-dd");
				}
				if (isFirstColumn) {
					isFirstColumn = false;
					deleteSQL.append(" `").append(reportColumn.getColumnName()).append("`").append("= ?");
				} else {
					deleteSQL.append(" and  `").append(reportColumn.getColumnName()).append("`").append("= ?");
				}
				paramConditions.add(dateObject);
				paramNames.add(reportColumn.getColumnName());
				continue;
			}

			if (StringUtils.containsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.NUMBER)
					|| StringUtils
							.containsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.INTEGER)) {
				Double numberObject = null;

				if (reportColumn.isNullable() && StringUtils.isBlank(requestParamValue)) {
					continue;
				}

				try {
					numberObject = Double.parseDouble(requestParamValue);
				} catch (Exception e) {
					logger.debug("Invalid number entered for" + reportColumn.getColumnName() + "..:"
							+ requestParamValue, e);
					SystemContext.getInstance().getUniqueMessage().set(
							"Invalid number entered for" + reportColumn.getColumnName());
					SystemContext.getInstance().getMessages().add(
							"Invalid number entered for" + reportColumn.getColumnName());
					return;
				}

				if (isFirstColumn) {
					isFirstColumn = false;
					deleteSQL.append(" `").append(reportColumn.getColumnName()).append("`").append("= ?");
				} else {
					deleteSQL.append(" and  `").append(reportColumn.getColumnName()).append("`").append("= ?");
				}
				paramConditions.add(numberObject);
				paramNames.add(reportColumn.getColumnName());
				continue;

			}

			if (StringUtils.equalsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.TINYINT)
					|| StringUtils.equalsIgnoreCase(reportColumn.getColumnType(), SystemConstants.ColumnTypes.BOOLEAN)) {
				if (StringUtils.equalsIgnoreCase(requestParamValue, "on")) {
					requestParamValue = "1";
				} else {
					requestParamValue = "0";
				}
			}

			if (!StringUtils.isBlank(requestParamValue)) {
				if (isFirstColumn) {
					isFirstColumn = false;
					deleteSQL.append(" `").append(reportColumn.getColumnName()).append("`").append("= ?");
				} else {
					deleteSQL.append(" and  `").append(reportColumn.getColumnName()).append("`").append("= ?");
				}
				paramConditions.add(requestParamValue);
				paramNames.add(reportColumn.getColumnName());
			}

		}

		/**
		 * In Rico _k0 Represents 0th key where in we can have multiple keys for
		 * given record
		 */
		System.out.println(deleteSQL.toString());

		FrameworkApplication app = SystemContext.getInstance().getUserContext().getFrameworkUser()
				.getListOfApplications().get(0);

		DBUpdateStatement dbUpdateStatement = new DBUpdateStatement();
		dbUpdateStatement.setTableName(reportObject.getFrameworkTable().getTableName());
		dbUpdateStatement.setArguments(paramConditions);
		dbUpdateStatement.setColumnNames(paramNames);
		dbUpdateStatement.setDatasourceName(datasourceName);
		dbUpdateStatement.setApplication(app);

		if (StringUtils.equalsIgnoreCase(app.getDatasourceType(), SystemConstants.DBTypes.SQLSERVER)) {
			dbUpdateStatement.setUpdateStatement(deleteSQL.toString().replaceAll("`", "\""));

			/*
			 * getPlatformDAO().update(deleteSQL.toString().replaceAll("`",
			 * "\""), datasourceName,
			 * paramConditions.toArray());
			 */
		} else if (StringUtils.equalsIgnoreCase(app.getDatasourceType(), SystemConstants.DBTypes.ORACLE)) {
			dbUpdateStatement.setUpdateStatement(deleteSQL.toString().replaceAll("`", ""));

			/*
			 * getPlatformDAO()
			 * .update(deleteSQL.toString().replaceAll("`", ""), datasourceName,
			 * paramConditions.toArray());
			 */
		} else {
			dbUpdateStatement.setUpdateStatement(deleteSQL.toString());
		}

		getPlatformDAO().addNewTransactionForTable(dbUpdateStatement);
		SystemContext.getInstance().getApprovalMap().put(reportObject.getFrameworkTable().getTableName(),
				dbUpdateStatement);
	}

	/*
	 * * (non-Javadoc)
	 * 
	 * @see
	 * com.northalley.framework.service.PlatformService#loadLovValuesData(com
	 * .northalley.framework.dataobject.FrameworkTextReport)
	 */
	public List<FrameworkLOVValue> loadLovValuesData(FrameworkTextReport reportObject) {
		String distinct = getRequestParamterWithNoEvaluation("distinct");
		String edit = getRequestParamterWithNoEvaluation("edit");
		String id = getRequestParamterWithNoEvaluation("id");
		String page_size = getRequestParamterWithNoEvaluation("page_size");

		logger.debug("distinct :" + distinct + "    edit :" + edit + "    id :" + id + "    page_size :" + page_size);

		if (StringUtils.isBlank(edit) && StringUtils.isNotBlank(page_size)
				&& StringUtils.equalsIgnoreCase(page_size, "-1")) {
			// For Filters
			logger.debug("In page_size For LOV");
			FrameworkReportColumn column = reportObject.getColumnByName(id);
			if (StringUtils.equalsIgnoreCase(column.getColumnType(), SystemConstants.ColumnTypes.LOV)) {
				return getPlatformDAO().loadLOVValues(column.getColumnDefaultValue());
			}
		} else if (StringUtils.isNotBlank(distinct)) {
			// For Filters
			logger.debug("In Distict For LOV");
			FrameworkReportColumn column = reportObject.getColumns().get(Integer.parseInt(distinct));
			if (StringUtils.equalsIgnoreCase(column.getColumnType(), SystemConstants.ColumnTypes.LOV)) {
				return getPlatformDAO().loadLOVValues(column.getColumnDefaultValue());
			}
		} else if (StringUtils.isNotBlank(edit)) {
			// For Form
			logger.debug("In Edit For LOV");
			FrameworkReportColumn column = reportObject.getColumns().get(Integer.parseInt(edit));
			if (StringUtils.equalsIgnoreCase(column.getColumnType(), SystemConstants.ColumnTypes.LOV)) {
				return getPlatformDAO().loadLOVValues(column.getColumnDefaultValue());
			}
		}

		logger.debug("returning LOV");
		return Collections.EMPTY_LIST;
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @see com.northalley.framework.service.PlatformService#getResultSet(java.lang .String, boolean)
	 */
	public ResultSet getResultSet(String sql, String dataSourceTemplate) {
		return getPlatformDAO().getResultSet(sql, dataSourceTemplate);
	}

	/**
	 * @return
	 */
	public boolean isUserValid() {
		String mediUser = SystemContext.getInstance().getUserContext().getUserId();
		String mediPassword = SystemContext.getInstance().getUserContext().getPassword();
		String mediSchema = SystemContext.getInstance().getUserContext().getSchemaName();

		if (mediUser != null) {
			KeyPair keys = SystemContext.getInstance().getKeys();

			try {
				if (keys != null) {
					String utf8String = new String(mediPassword.trim().getBytes("utf-8"));
					String password = JCryptionUtil.decrypt(utf8String, keys);
					password = password.substring(2);

					String loginUserSQL = "SELECT * FROM " + mediSchema + ".MEDI_USERS WHERE USER_ID ='" + mediUser
							+ "' AND USER_PASSWORD='" + password + "'";

					ResultSet resultSet = getPlatformDAO().getResultSet(loginUserSQL, "frameworkJdbcTemplate");
					if (resultSet != null && resultSet.next()) {
						SystemContext.getInstance().getLoggedInUsers().put(mediUser, mediPassword);
						return true;
					} else {
						return false;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#loadExcelFile (java.lang.String)
	 */
	public void loadExcelFile(ExcelFile excelFile) {
		/**
		 * Load Data from excel file into table created....
		 */
		getPlatformDAO().loadExcelFile(excelFile);
		/**
		 * Load Lov files from excel Into Report
		 */
		if (StringUtils.equalsIgnoreCase(excelFile.getExcelType(), ExcelFile.ExcelTypes.COMPLEXTYPE)) {
			loadLovData(excelFile);
		}
		/**
		 * Generate Text reports and Menu
		 */
		// connectAndGenerateReports(excelFile);
	}

	/**
	 * Load Lov Data into system from excel file...
	 * 
	 * @param excelFile
	 */
	private void loadLovData(ExcelFile excelFile) {
		for (String lovName : excelFile.getExcelTabs().get(1).getLovValuesMapping().keySet()) {
			FrameworkLOV lov = new FrameworkLOV();
			lov.setLovDescription(lovName);
			lov.setLovID(lovName);
			lov.setLovLabel(lovName);
			lov.setLovName(lovName);
			lov.setLovSQL("SELECT LOV_VALUE,LOV_VALUE_LABEL FROM FRM_LOV_VALUES WHERE LOV_ID = '" + lovName + "'");
			lov.setLovType(FrameworkLOV.LovTypes.SQL);

			getPlatformDAO().saveLov(lov);

			List<String> lovValues = excelFile.getExcelTabs().get(1).getLovValuesMapping().get(lovName);
			for (String lovValue : lovValues) {
				FrameworkLOVValue frameworkLOVValue = new FrameworkLOVValue();
				frameworkLOVValue.setLovId(lovName);
				frameworkLOVValue.setLovValue(lovValue);
				frameworkLOVValue.setLovValueLabel(lovValue);

				getPlatformDAO().saveLovValue(frameworkLOVValue);
			}

		}
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @seecom.linkwithweb.products.swiftui.service.PlatformService#
	 *                                                               loadAndStoreDataSource
	 *                                                               (java.lang.
	 *                                                               String,
	 *                                                               java.lang.
	 *                                                               String,
	 *                                                               java.lang.String
	 *                                                               , java.lang
	 *                                                               .String)
	 */
	public void loadAndStoreDataSource(String dbUrl, String dbType, String username, String password) {
		FrameworkApplication app = SystemContext.getInstance().getUserContext().getFrameworkUser()
				.getListOfApplications().get(0);
		getPlatformDAO().loadAndStoreDataSource(app.getDbUrl(), app.getDbDriver(), app.getDbUsername(),
				app.getDbPassword());
		// connectAndGenerateReports(null);
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @seecom.linkwithweb.products.swiftui.service.PlatformService#
	 *                                                               connectAndGenerateReports
	 *                                                               ()
	 */
	public void connectAndGenerateReports(ExcelFile excelFile) {
		String clientIdentifier = SystemContext.getInstance().getUserContext().getIdentifier();
		getPlatformDAO().connectAndGenerateReports(excelFile, clientIdentifier);
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#loadUser(java .lang.String, java.lang.String)
	 */
	public FrameworkUser loadUser(String userName, String password) {
		return getPlatformDAO().loadUser(userName, password);
	}

	public FrameworkWorkflow loadWorkflowForTable(String tableId) {
		return getPlatformDAO().loadWorkflowForTable(tableId);
	}

	public FrameworkTransaction loadLastWorkflowTransaction(String tableId) {
		return getPlatformDAO().loadLastWorkflowTransaction(tableId);
	}

	public List<FrameworkTransaction> loadWorkflowTasks() {
		return getPlatformDAO().loadWorkflowTasks();
	}

	public FrameworkWorkflow loadWorkflowForTransaction(FrameworkTransaction transaction) {
		return getPlatformDAO().loadWorkflowForTransaction(transaction);
	}

	public void addNewTransactionForTable(DBUpdateStatement stmt) {
		getPlatformDAO().addNewTransactionForTable(stmt);
	}

	public void changeTransactionStatus(FrameworkTransaction transaction, String newApprovalStatus) {
		getPlatformDAO().changeTransactionStatus(transaction, newApprovalStatus);
	}

	public FrameworkTransaction loadWorkflowTransaction(String transactionId) {
		return getPlatformDAO().loadWorkflowTransaction(transactionId);
	}

	public void executeScript(String sqlScriptPath, String dataSourceName) {
		getPlatformDAO().executeScript(sqlScriptPath, dataSourceName);
	}

	public void generateReport(String reportName, String sql, Map<String, Object> parameters, OutputStream out) {
		getPlatformDAO().generateReport(reportName, sql, parameters, out);
	}

	public void uploadFile(FrameworkUpload upload) {
		getPlatformDAO().uploadFile(upload);
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#getFilesByTag (java.lang.String)
	 */
	public List<FrameworkUpload> getFilesByTag(String tagName) {
		return getPlatformDAO().getFilesByTag(tagName);
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#loadEvent(java.lang.String, int)
	 */
	@Override
	public FrameworkEvent loadEvent(String schedulerId, int uniqueKey) {
		// TODO Auto-generated method stub
		return getPlatformDAO().loadEvent(schedulerId, uniqueKey);
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#loadEventScheduler(java.lang.String)
	 */
	@Override
	public FrameworkEventScheduler loadEventScheduler(String schedulerId) {
		// TODO Auto-generated method stub
		return getPlatformDAO().loadEventScheduler(schedulerId);
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#loadEvents(java.lang.String)
	 */
	@Override
	public List<FrameworkEvent> loadEvents(String schedulerId, Map<String, String> arguments) {
		// TODO Auto-generated method stub
		return getPlatformDAO().loadEvents(schedulerId, arguments);
	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#saveOrUpdateEvent(com.linkwithweb.products.swiftui.dataobject.FrameworkEvent)
	 */
	@Override
	public void saveOrUpdateEvent(FrameworkEvent frameworkEvent) {
		getPlatformDAO().saveOrUpdateEvent(frameworkEvent);

	}

	/**
	 ** (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#saveOrUpdateEventScheduler(com.linkwithweb.products.swiftui.dataobject.FrameworkEventScheduler)
	 */
	@Override
	public void saveOrUpdateEventScheduler(FrameworkEventScheduler frameworkEventScheduler) {
		getPlatformDAO().saveOrUpdateEventScheduler(frameworkEventScheduler);

	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#deleteEvent(com.linkwithweb.products.swiftui.dataobject.FrameworkEvent)
	 */
	public void deleteEvent(FrameworkEvent event) {
		getPlatformDAO().deleteEvent(event);
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.linkwithweb.products.swiftui.service.PlatformService#getResourcesForScheduler(com.linkwithweb.products.swiftui.dataobject.FrameworkEventScheduler)
	 */
	public List<MapObject> getResourcesForScheduler(FrameworkEventScheduler frameworkEventScheduler, Map<String, Object> arguments) {
		String userIdColumn = frameworkEventScheduler.getUserIdColumn();
		String schemaName = frameworkEventScheduler.getSchemaName();
		String tableName = frameworkEventScheduler.getTableName();

		StringBuffer resourceSQL = new StringBuffer("SELECT distinct ");
		resourceSQL.append(userIdColumn).append(" as USER_ID_COLUMN FROM ").append(schemaName).append(".").append(
				tableName).append(" WHERE 1=1 ");

		/**
		 * Note: Key contains both column name and operator (Ex: distance <)
		 */
		int offset = 0;
		int rowCount = 5;
		for (String key : arguments.keySet()) {
			if (StringUtils.equalsIgnoreCase("offset", key)) {
				offset = Integer.parseInt((String) arguments.get(key));
				continue;
			}
			if (StringUtils.startsWithIgnoreCase(key, "NONE") || arguments.get(key) == null) {
				continue;
			}
			resourceSQL.append(" AND ").append(key).append(arguments.get(key));
		}

		resourceSQL.append(" LIMIT ").append(offset).append(",").append(rowCount);

		return getPlatformDAO().getResourcesForScheduler(resourceSQL.toString());
	}

	/**
	 * @param backup
	 */
	public void saveBackupDetails(FrameworkBackup backup) {

		getPlatformDAO().saveBackupDetails(backup);
	}

	/**
	 * @param backupId
	 * @return
	 */
	public FrameworkBackup loadBackupById(String backupId) {
		return getPlatformDAO().loadBackupById(backupId);
	}

	/**
	 * @return
	 */
	public List<FrameworkBackup> loadBackups() {
		return getPlatformDAO().loadBackups();

	}
}
